﻿using System;
using System.Collections.Generic;
using System.Net.Mime;
using System.Text;

namespace Conusic.Model.Audio.Server
{
    public enum ServerHeaderType
    {
        Ok = 0,
        Redirect = 1,
        NotFound = 2
    }

    internal class ServerHeader
    {
        public ServerHeaderType headerType;

        private static readonly string[] StatusLine = {
                                                         "200 OK", // OK
                                                         "302 Found", // Redirect
                                                         "404 Not Found" // Not Found
                                                     };

        private readonly Dictionary<string, string> headers = new Dictionary<string, string>();

        public ServerHeader()
        {
            headerType = ServerHeaderType.Ok;
            headers.Add("Server", "Conusic www");
            headers.Add("Connection", "close");
            headers.Add("Content-Type", "text/html; charset=utf-8");
        }

        public ServerHeader(ServerHeaderType headerType) : this()
        {
            this.headerType = headerType;
        }

        public ServerHeader(ServerHeaderType headerType, string location) : this(headerType)
        {
            headers.Add("Location", location);
        }

        public void SetHeader(string fieldName, string fieldValue= "")
        {
            if (fieldName == null) throw new ArgumentNullException("fieldName");
            headers[fieldName] = fieldValue;
        }

        public override string ToString()
        {
            var result = new StringBuilder();
            result.AppendFormat("HTTP/1.1 {0}\r\n",StatusLine[(int)headerType] );

            foreach (var header in headers)
            {
                result.AppendFormat("{0}: {1}\r\n",header.Key, header.Value);
            }
            result.Append("\r\n");

            return result.ToString();
        }
    }
}